import React, {useEffect, useState} from 'react'
// @ts-ignore
import type {BuiltInControlType, ControlType, ExtendControlType} from "braft-editor";
import BraftEditor from "braft-editor";
import 'braft-editor/dist/index.css'
import {message, Upload} from "antd";
// @ts-ignore
import { ContentUtils } from 'braft-utils'
import COS from "cos-js-sdk-v5";
import type {RcFile} from "antd/lib/upload/interface";
import {isSuccess} from "@/utils/utils";
import {getUploadConfig} from "@/components/UploadForm";

interface EditContentProps {
  onChange: Function,
  initValue?: string,
  controls?: ControlType[];
  excludeControls?: BuiltInControlType[];
  extendControls?: ExtendControlType[];
}

const RichEditor: React.FC<EditContentProps> = ({ initValue, onChange, controls, excludeControls, extendControls}) => {

  const [editorState, setEditorState] = useState<any>(BraftEditor.createEditorState(initValue ?? "")) // 存储 editor 实例

  const [upConfig, setUpConfig] = useState<any | undefined>(undefined);

  useEffect(() => setEditorState(BraftEditor.createEditorState(initValue ?? "")), [initValue])

  // const controls = ['bold', 'italic', 'underline', 'text-color', 'separator', 'link', 'separator']
  const excludeDefault: BuiltInControlType[] = ['media']

  const extendControlsDefault: ExtendControlType[] = [
    {
      key: 'antd-uploader',
      type: 'component',
      component: <Upload
        accept="image/*"
        showUploadList={false}
        customRequest={(option: any) => {
          if(upConfig){
            const file = option.file as File
            try {
              const cos = new COS({
                getAuthorization:(options: any, callback: Function)=>{
                  callback({
                    TmpSecretId: upConfig.tmpSecretId,
                    TmpSecretKey: upConfig.tmpSecretKey,
                    SecurityToken: upConfig.sessionToken,
                    StartTime: upConfig.startTime,
                    ExpiredTime: upConfig.expiredTime
                  })
                }
              })
              // 使用第三方服务进行文件上传
              cos.putObject({
                Bucket: upConfig?.bucket, /* 必须 */
                Region: upConfig?.region,    /* 必须 */
                Key:  upConfig?.key,              /* 必须 */
                StorageClass: 'STANDARD',
                Body: file, // 上传文件对象
                onProgress: function(progressData) {
                  console.log(JSON.stringify(progressData));
                  if(progressData.percent==1){
                    setEditorState(ContentUtils.insertMedias(editorState, [{
                      type: 'IMAGE',
                      url: upConfig?.url
                    }]))
                    option.onSuccess(upConfig?.url)
                  }
                },
              }, function(err, data) {
                console.log(err || data);
              });
            } catch (error) {
              option.onError(error)
            }
          }else{
            message.error('上传出错，请重试')
            option.onError('上传出错，请重试')
          }
        }}
        beforeUpload={
          (file: RcFile) => new Promise((resolve, reject) => getUploadConfig('public', file.name)
            .then(({code, data}: any) => {
              if (isSuccess(code)) {
                setUpConfig(data ?? undefined)
                resolve(file)
              } else {
                message.error('上传出错，请刷新重试')
                reject()
              }
            }))
        }
      >
        <button type="button" className="control-item button upload-button" data-title="插入图片">插入图片</button>
      </Upload>
    }
  ]

  // @ts-ignore
  return <div className="editor-wrapper">
    <BraftEditor
      value={editorState}
      controls={controls}
      onChange={state => {setEditorState(state); onChange?.(state.toHTML())}}
      extendControls={[...extendControlsDefault, ...(extendControls ? extendControls : [])]}
      excludeControls={[...excludeDefault, ...(excludeControls ? excludeControls : [])]}
    />
  </div>
};


export default RichEditor;
